package com.faithbj.controller.process;

import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.HandleStatus;
import com.faithbj.process.*;
import com.faithbj.process.stats.JbpmStatsService;
import com.faithbj.support.fp.Tuple3;
import com.faithbj.support.fp.Tuple6;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * User: xiongyuanwei
 * Date: 12-7-7
 * Time: 下午2:52
 */
@Controller
@RequestMapping("/process")
public class ProcessController {

    @Autowired
    private ProcessQueryService processQueryService;

    @Autowired
    private ProcessApplicationService processApplicationService;

    @Autowired
    @Qualifier("jbpmStatsServiceImpl")
    private JbpmStatsService jbpmStatsService;

    @RequestMapping("/start")
    public String start(String applyId, String userId, boolean success, String memo, ModelMap model) {
        CheckTotal checkTotal = new CheckTotal();
        checkTotal.setId(applyId);
        checkTotal.setHandleUser(userId);
        checkTotal.setHandleStatus(success ? HandleStatus.HANDLE : HandleStatus.NOT_HANDLE);
        checkTotal.setHandleMemo(memo);
        checkTotal.setHandleTime(new Date());
        processApplicationService.startAndFinishArriveTask(checkTotal);
        return "/processtest/start";
    }

    @RequestMapping("/all")
    public String listAllCurrentTasks(int first, int limit, ModelMap model) {
        List<TaskModel> tasks = processQueryService.listAllAvailableTasksWithContent(first, limit);
        model.put("tasks", tasks);
        return "/processtest/list";
    }

    @RequestMapping("/{userId}/{stateId}/list")
    public String listACurrentTasksByUserAndState(@PathVariable String userId, @PathVariable int stateId,
                                                  int first, int limit, ModelMap model) {
        State state = State.values()[stateId - 1];
        TaskModelFilter filter = new ExcludedOwnerTaskModelFilter(userId);
        int count = processQueryService.countAvailableTasksByUserAndState(userId, state, filter);
        List<TaskModel> tasks = processQueryService.listAvailableTasksWithContentByUserAndState(
                userId, state, first, limit, filter);
        model.put("count", count);
        model.put("tasks", tasks);
        return "/processtest/list";
    }

    @RequestMapping("/{stateId}/all")
    public String listAllCurrentTasks(@PathVariable int stateId, int first, int limit, ModelMap model) {
        List<TaskModel> tasks = processQueryService.listAllAvailableTasksWithContentByState(
                State.values()[stateId - 1], first, limit);
        model.put("tasks", tasks);
        return "/processtest/list";
    }

    @RequestMapping("/search")
    public String search(CheckTotalCondition condition, String userId, int stateId, int first, int limit, ModelMap model) {
        condition.setAcceptDateFrom(new Date(0));
        State state = State.values()[stateId - 1];
        List<TaskModel> tasks = processApplicationService.search(condition, state, first, limit);
        model.put("tasks", tasks);
        return "/processtest/list";
    }

    @RequestMapping("/stats1")
    public String stats1(String[] applyIds, ModelMap model) {
        Map<String, Tuple6<State, String, Date, Date, Date, Date>> map = jbpmStatsService.getApplyDetailsByApplyIds(Arrays.asList(applyIds));
        model.put("map", map);
        return "/processtest/stats1";
    }

    @RequestMapping("/stats2/{regionId}/{from}-{to}")
    public String stats2(@PathVariable String regionId, @PathVariable String from, @PathVariable String to, ModelMap model) throws ParseException {
        if (StringUtils.isBlank(from)) {
            from = "1970-01-01";
        }
        if (StringUtils.isBlank(to)) {
            to = "2099-01-01";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date fromDate = dateFormat.parse(from);
        Date toDate = dateFormat.parse(to);
        Map<String, Map<State, Long>> map = jbpmStatsService.countGroupByApplyStateInRegion(regionId, fromDate, toDate);
        List<Tuple3<String, String, Long>> values = Lists.newLinkedList();
        for (Map.Entry<String, Map<State, Long>> entry : map.entrySet()) {
            String rid = entry.getKey();
            Map<State, Long> stateCounts = entry.getValue();
            for (Map.Entry<State, Long> e : stateCounts.entrySet()) {
                values.add(new Tuple3<String, String, Long>(rid, e.getKey().getName(), e.getValue()));
            }
        }
        model.put("values", values);
        return "/processtest/stats2";
    }
}
